/**
 * 
 */
package com.ly.hotel.view.fragments.vod;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.SharedPreferencesConfig;
import com.ly.hotel.model.VodVideoBean;
import com.ly.hotel.model.Vodpart;
import com.ly.hotel.model.Vodvideo;
import com.ly.hotel.msgevent.GetVodSearchVideoEvent;
import com.ly.hotel.msgevent.GetVodTypeListEvent;
import com.ly.hotel.msgevent.GetVodVideoEvent;
import com.ly.hotel.msgevent.UpdateVodSearchVideoEvent;
import com.ly.hotel.msgevent.UpdateVodTypeListEvent;
import com.ly.hotel.msgevent.UpdateVodVideoEvent;
import com.ly.hotel.util.LanguageUtil;
import com.ly.hotel.util.ProcessWaitingUtil;
import com.ly.hotel.util.ToastUtil;
import com.ly.hotel.view.MlistView;
import com.ly.hotel.view.common.BaseActivity;
import com.ly.hotel.view.common.CloudAdShowActivity;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * @author jouson 2015-1-10
 */
public class VodActivity extends BaseActivity {

	private static final String TAG = "VodActivity";
	// 电影类别的名字列表Adapter
	private VodHeadAdapter vodTypeListAdapter;
	// 电影类型Listview
	private MlistView movieTypeListView;
	// 电影分类的名字在这里
	private List<Vodpart> movieTypeList = new ArrayList<>();
	private Vodpart typeListIndex = null;

	private GridView mGridView;

	// 这两个只是当前的list，会变的,每次调用updateVodItem()的时候，都要刷新一下
	private ArrayList<Vodvideo> gridviewList1 = new ArrayList<>();
	private MyApplication app;


	private int tryTimes = 3;
	private ThisHandler handlerMsg = new ThisHandler(this);
	public Vodvideo video;
	
	public Button searchBtn;
	public Button historyBtn;
	
	private LinearLayout downMore;
	private EditText searchKeyText;
	private TextView totalText;
	private TextView nameText;
	private String updateName;
	private ImageView vodDownMore;
	public int searchDelayTime = 1500;//搜索输入停顿1.5秒之后自动发起搜索
	private Dialog popWinDilog;
	private String keys[] = {"A","B","C","D","E","F","G","H","I","J",
							"K","L","M","N","O","P","Q","R","S","T",
							"U","V","W","X", MyApplication.getContext().getString(R.string.movie_search_clear),
							"Y","Z", MyApplication.getContext().getString(R.string.movie_search_exit)};

	public static final int INIT_VIEW =  2;
	public static final int SEARCH_VIDEO =  3;

	private VodItemAdapter mRecAdapter;
	private int selectPos = -1;
	private int top;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_vod);
		app = (MyApplication) getApplicationContext();
		app.vodsList.clear();	//清掉剧集列表
		top = getResources().getDimensionPixelSize(R.dimen.px12);
		findView();
		setListener();
		// 获取电影分类列表
		handlerMsg.sendEmptyMessageDelayed(INIT_VIEW, 200);
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i(TAG, "onDestroy");
	}

	@Override
	public void finish() {
		super.finish();
	}


	@Override
	public void onPause() {
		if(handlerMsg.hasMessages(INIT_VIEW)){
			handlerMsg.removeMessages(INIT_VIEW);
		}
		super.onPause();
	}

	private void initProgramDailog() {

		popWinDilog = new Dialog(getBaseContext(), R.style.vodPopDialog);
		popWinDilog.setCanceledOnTouchOutside(true);
		Window dialogWindow = popWinDilog.getWindow();
		dialogWindow.setGravity(Gravity.LEFT | Gravity.CENTER);
        popWinDilog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		popWinDilog.show();
		popWinDilog.setContentView(R.layout.popwin_vod_search);

		searchKeyText =  popWinDilog.findViewById(R.id.searchKey);
		GridLayout mll = popWinDilog.findViewById(R.id.keyBoardPad);

		int marginInt = getResources().getDimensionPixelSize(R.dimen.px3);
		int layoutInt = getResources().getDimensionPixelSize(R.dimen.px84);
		for ( String key:keys) {
			Button tmpBtn = new Button(getBaseContext());
			tmpBtn.setTag(key);
			tmpBtn.setText(key);
			tmpBtn.setPadding(0,0,0,0);
			tmpBtn.setBackgroundResource(R.drawable.act_keyboard_btn);
			tmpBtn.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.px30));
			GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
			layoutParams.width = layoutInt;
			layoutParams.height = layoutInt;
			layoutParams.setMargins(marginInt,marginInt,marginInt,marginInt);
			tmpBtn.setLayoutParams(layoutParams);
			mll.addView(tmpBtn);
			tmpBtn.setOnClickListener(btnTouchListenter);
		}
	}
	
	private OnClickListener btnTouchListenter = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			String key = arg0.getTag().toString();
				Log.i("vod", "按下虚拟键盘:" + key);
				//如果还有没有发出去的搜索请求，就删除之，准备重新发送
				if(handlerMsg.hasMessages(SEARCH_VIDEO)){
					handlerMsg.removeMessages(SEARCH_VIDEO);
				}
				
				if(key.equals(getString(R.string.movie_search_clear))){
					searchKeyText.setText("");
				}else if(key.equals(getString(R.string.movie_search_exit))){
					closeProgramDailog();
				}else {
					if(searchKeyText.getText().toString().length() < 15){
						searchKeyText.append(key);

						if(searchKeyText.getText().toString().equals("PREGOOD")){
							closeProgramDailog();
							Intent intent = new Intent(Intent.ACTION_MAIN);
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							intent.setClassName("com.ly.hotel", "com.ly.hotel.view.setting.SystemSettingActivity");
							startActivity(intent);
						} else if(searchKeyText.getText().toString().equals("PREVIP")){
							closeProgramDailog();
							//可以留位一个小时
							app.setLiuweiTime(60);
						}else {
							if(handlerMsg.hasMessages(SEARCH_VIDEO)){
								handlerMsg.removeMessages(SEARCH_VIDEO);
							}
							handlerMsg.sendEmptyMessageDelayed(SEARCH_VIDEO, searchDelayTime);
						}
					}else{
						Toast.makeText(VodActivity.this, "输入限制！Restrict input！", Toast.LENGTH_SHORT).show();
					}
				}
			}
	};
	
	//不是真正的播放电影，而是去检测是否有广告需要播放
	@SuppressLint("DefaultLocale")
	public void play(Vodvideo v) {
		String url = v.getPath();
		Log.i(TAG, "将要播放" + v.getName());
		boolean flag = false;
		if(MyApplication.licenseTimeOut && MyApplication.ukeyInvalidDays >= 0){
			//U盾过去，过去时间一天
			if(MyApplication.ukeyInvalidDays > 0){
				//U盾过去，过去时间一天以上
				Log.i(TAG, "Ukey的过期了，禁止看电影!");
			} else if(MyApplication.startUpTimeHour >= 14){
				Log.i(TAG, "Ukey的过期了，禁止看电影!");
			}
		} else if(!SharedPreferencesConfig.getMovieEnable(this)){
			ToastUtil.showShortToast(this, "尊敬的贵宾:本区域暂不支持视频播放功能", Toast.LENGTH_LONG);
		} else {
			if (url != null) {
				
				//保存播放历史,有就算数，没有就加进去
				if(app.vodHistory.isEmpty()){
					flag = true;
				}else{
					for(Vodvideo vv : app.vodHistory){
						flag = true;
						if(vv.getId().equals(v.getId())){
							flag = false;
							break;
						}
					}
				}
				
				if(flag){
					Log.i(TAG, "加入历史:" + v.getName());
					app.vodHistory.add(v);
				}
				
				//需要将路径转码，再合并,‘/’斜杠是不需要转码的
				String group[] = url.split("/");
				url = "";
				
				for(String s : group){
					url += "/";
					try {
						//由于空格转码后为+号，所以替换+号成%20
						url += URLEncoder.encode(s, "utf-8").replaceAll("\\+","%20");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
				//////////////////////////
				String tmp[] =  MyApplication.getHostIp().split(":");
				if(tmp.length == 2 && !v.getServerPort().equals("0")){
					url = "http://" + tmp[0] + ":" + v.getServerPort() + "/" + url;
				}else{
					url = MyApplication.getHostResUrl() + url;
				}
				Log.i(TAG,v.getName() + " url=" + url);
				
				Intent intent = new Intent(MyApplication.getContext(), CloudAdShowActivity.class);
				intent.putExtra("actionType", "vod");
				intent.putExtra("path", url);
				intent.putExtra("filmName", v.getName());
				intent.putExtra("position", v.getPlayPosition());
				
				if(typeListIndex != null){
					intent.putExtra("filmArea", typeListIndex.getVodpartname());
				}else{
					intent.putExtra("filmArea", "未知类型");
				}
				intent.putExtra("filmId", v.getId());
				this.startActivity(intent);

			} else {
				Log.i(TAG, "videoUrl=null---请联系后台管理员添加视频！");
				Toast.makeText(getApplicationContext(), "没有找到该视频", Toast.LENGTH_SHORT).show();
			}
		}
	}

	private void findView() {
		movieTypeListView = findViewById(R.id.movieTypeListViewA);
		searchBtn = findViewById(R.id.searchBtnA);
		totalText = findViewById(R.id.vod_count);
		nameText = findViewById(R.id.vod_name);
		downMore = findViewById(R.id.down_more);
		historyBtn = findViewById(R.id.historyBtnA);
		mGridView = findViewById(R.id.mVodRecycleView);
		vodDownMore = findViewById(R.id.vod_down_more);
		LinearLayout tvBtn = findViewById(R.id.tvButton);
		tvBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intente = new Intent(VodActivity.this, EpisodeActivity.class);
				startActivity(intente);
			}
		});
	}
	
	private void updateTypeListView() {
		/* 初始化类型 */
		if (MyApplication.getVodpart() != null && !MyApplication.getVodpart().isEmpty()) {
			if (MyApplication.getVodpart().size() > 0) {
				// 清掉再加
				movieTypeList.clear();
				for (Vodpart vodpat : MyApplication.getVodpart()) {
					if(!vodpat.getVodpartname().startsWith("TV_")){
							movieTypeList.add(vodpat);
					}
				}
				if(movieTypeList.size() >= 1){
	
					// 使用自定义的Adapter 
					vodTypeListAdapter = new VodHeadAdapter(this, movieTypeList);
					movieTypeListView.setAdapter(vodTypeListAdapter);
					
					
					//模拟第一行点击
					movieTypeListView.post(new Runnable(){
					    public void run(){
					    	int count = movieTypeListView.getChildCount();
					        if (count != 0){ 					        	
					        	movieTypeListView.performItemClick(movieTypeListView.getChildAt(0), 
					        			0, movieTypeListView.getItemIdAtPosition(0));
						        movieTypeListView.requestFocus();
						        movieTypeListView.requestFocusFromTouch();
						        movieTypeListView.setSelection(0);
					        } 					 
					    }
					  
					});										
				}
			}
		} else {
			if(tryTimes>0){
				tryTimes--;
				EventBus.getDefault().post(new GetVodTypeListEvent());
				ProcessWaitingUtil.showProcessDialog(this, "获取视频列表数据中..", 3000);
			}
		}

	}

	private void setListener() {
		movieTypeListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
				VodHeadAdapter.ViewHolder holder = (VodHeadAdapter.ViewHolder)view.getTag();
				updateName = LanguageUtil.getTextFromLocalLanguage(holder.v.getVodpartname());
				vodTypeListAdapter.setSelectedPosition(pos);
				vodTypeListAdapter.notifyDataSetChanged();
				if (typeListIndex != holder.v) {
					typeListIndex = holder.v;
										
					// 有数据就显示
					ProcessWaitingUtil.showProcessDialog(VodActivity.this, "Loading..", 3000);
					if (updateVodItemList(typeListIndex)) {
						updateVodItemView();
					} else {// 没数据就请求一组
						//清空掉，这样不会有残留上一个分类的视频
						gridviewList1.clear();
						EventBus.getDefault().post(new GetVodVideoEvent(holder.v));
					}		
				}
			}
		});
		
		movieTypeListView.setOnScrollListener(new AbsListView.OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {
			}
			
			/* (non-Javadoc)
			 * @see android.widget.AbsListView.OnScrollListener#onScroll(android.widget.AbsListView, int, int, int)
			 */
			@Override
			public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
				if ((arg1 == 0 && arg2 == arg3) || (arg1 > 0 && arg1+arg2 == arg3)) {
		        	downMore.setVisibility(View.GONE);
		        }  else {
		        	downMore.setVisibility(View.VISIBLE);
		        }
			}
		});

		mGridView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				if(selectPos != -1) {
					int dValue = selectPos - position;
					if (dValue == 5) {
						if(position > 4) {
							mGridView.smoothScrollToPositionFromTop(position -5,-top);
						}else{
							mGridView.smoothScrollToPositionFromTop(0,0);
						}
					} else if (dValue == -5) {
						if(position > 4) {
							mGridView.smoothScrollToPositionFromTop(position,top);
						}else{
							mGridView.smoothScrollToPositionFromTop(0,0);
						}
					}
				}
				selectPos = position;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				selectPos = -1;
			}
		});

		mGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if(scrollState == 0){
					ImageLoader.getInstance().resume();
				}else{
					ImageLoader.getInstance().pause();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				if((firstVisibleItem + visibleItemCount) == totalItemCount){
					vodDownMore.setVisibility(View.INVISIBLE);
				}else{
					vodDownMore.setVisibility(View.VISIBLE);
				}
			}
		});

		searchBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				showProgramDailog();
			}
		});

		mGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// 打开电影进行播放
				play(gridviewList1.get(position));
			}
		});
		
		historyBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				updateName = getResources().getString(R.string.movie_History);
				if(typeListIndex != null) {
					vodTypeListAdapter.setSelectedPosition(-1);
					typeListIndex = null;
				}
				updateVodHistoryList();
				updateVodItemView();
			}
		});
	}

	//找到数组中的最大值
	private int findMax(int[] lastPositions) {
		int max = lastPositions[0];
		for (int value : lastPositions) {
			if (value > max) {
				max = value;
			}
		}
		return max;
	}

	private void showProgramDailog(){
		if(popWinDilog != null){
			popWinDilog.show();
			popWinDilog.dismiss();
		}
		
		initProgramDailog();
	}
	
	private void closeProgramDailog() {
		if(popWinDilog != null){
			popWinDilog.dismiss();
			popWinDilog=null;
		}
	}
	
	private Boolean updateVodHistoryList() {
		Boolean rv = false;
		List<VodVideoBean> list = new ArrayList<>();
		List<Vodvideo> v;
		
		if(MyApplication.getVodpart() != null){
			/* 根据列表的类型索引获取改索引下的所有视频数据 */
	
			if (list != null) {
				v = app.vodHistory;
				gridviewList1.clear();
				gridviewList1.addAll(v);
				rv = true;
			}
		}
		return rv;
	}
	
	private Boolean updateVodItemList(Vodpart vodpart) {
		Boolean rv = false;
		List<VodVideoBean> list;
		List<Vodvideo> v = new ArrayList<>();
		gridviewList1.clear();
		if(MyApplication.getVodpart() != null){
			/* 根据列表的类型索引获取改索引下的所有视频数据 */
			list = vodpart.getVodvideoBeanList();
			if (list != null) {
				/* 将所有分页数据合并在一起 */
				for (VodVideoBean b : list) {
					v.addAll(b.getMovies());
				}
				gridviewList1.addAll(v);
				rv = true;
			}
		}
		return rv;
	}
	
	//把搜索到的电影显示出来
	private Boolean updateVodSearchItemList() {
		Boolean rv = false;
		
		/* 根据列表的类型索引获取改索引下的所有视频数据 */

		if (app.vodSearchVideos != null) {
			gridviewList1.clear();
			gridviewList1.addAll(app.vodSearchVideos.getMovies());			
			rv = true;
		}
		
		return rv;
	}

	//清空电影视频列表
	private void cleanViewItem(){
		gridviewList1.clear();
	}
		
	private void updateVodItemView(){
		nameText.setText(updateName);
		totalText.setText(gridviewList1.size()
				+ " " + getResources().getString(R.string.movie_videos));
		if (movieTypeList.size() == 0 || mGridView == null) {
			return;
		}

		selectPos = -1;
		if(mRecAdapter == null){
			mRecAdapter = new VodItemAdapter(this,gridviewList1);
			mGridView.setAdapter(mRecAdapter);
		}else{
			mRecAdapter.notifyDataSetChanged();
		}

		mGridView.post(new Runnable() {
			@Override
			public void run() {
				mGridView.setSelection(0);
				mGridView.smoothScrollToPositionFromTop(0,0);
				ProcessWaitingUtil.closeProcessDialog();
			}
		});
	}
	
	/* 这个只是一个事件，具体的信息需要app.getVodpart()获得 */
	public void onEventMainThread(UpdateVodVideoEvent e) {
		Log.i(TAG, "更新视频节目列表，typeListIndex=" + typeListIndex);
		updateVodItemList(typeListIndex);
		updateVodItemView();
	}

	public void onEventMainThread(UpdateVodTypeListEvent e) {
		Log.i(TAG, "更新视频节目类型列表");

		ProcessWaitingUtil.closeProcessDialog();
		updateTypeListView();
	}
	
	/* 这个只是一个事件，具体的信息需要app.getVodpart()获得 */
	public void onEventMainThread(UpdateVodSearchVideoEvent e) {

		if(typeListIndex != null) {
			vodTypeListAdapter.setSelectedPosition(-1);
			typeListIndex = null;
		}

		if (e.isValidUpdate()) {
			updateVodSearchItemList();
			updateVodItemView();
			typeListIndex = null;//搜索玩之后，显示的电影列表已经不是原来的那个了，所以必须要初始化这个值才行，否则左边有些类别按了没反应
		} else {
			//没有搜索到结果。。
			cleanViewItem();
			updateVodItemView();
		}
	}
	/**
	 * handler处理消息机制
	 */
	private static class ThisHandler extends Handler {
		private WeakReference<VodActivity> wrActivity;

		public ThisHandler(VodActivity activity) {
			wrActivity = new WeakReference<VodActivity>(activity);
		}

		@Override
		public void handleMessage(final Message message) {
			final VodActivity act = wrActivity.get();
			Log.i(TAG, "handleMessage="+message.what);
			if (act != null) {
				switch (message.what) {
				case INIT_VIEW:
					act.updateTypeListView();
					break;	
					
				//搜索
				case SEARCH_VIDEO:
					ProcessWaitingUtil.showProcessDialog(act, "搜索中...", 5000);
					act.updateName = act.searchKeyText.getText().toString();
					EventBus.getDefault().post(new GetVodSearchVideoEvent(act.searchKeyText.getText().toString()));
					break;
				}
			}
		}
	}
}
